package org.teemor.sca.nacosconsumer;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.teemor.sca.apis.SampleApi;

import java.util.concurrent.TimeUnit;

@SpringBootApplication
@EnableDiscoveryClient

public class NacosConsumerApplication {
    @RestController
    @RefreshScope
    public class NacosController{

        @Autowired
        private LoadBalancerClient loadBalancerClient;
        @Autowired
        private RestTemplate restTemplate;

        @Value("${user.name}")
        private String data;

        @GetMapping("/echo/app-name")
        @SentinelResource("app-name")
        public String echoAppName(){
            //Access through the combination of LoadBalanceClient and RestTemplate
//            ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-provider");
//            String path = String.format("http://%s:%s/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),data);
//            System.out.println("request path:" +path);
//            return restTemplate.getForObject(path,String.class);
            return sampleApi.echoServer(data);
        }

    }

    //Instantiate RestTemplate Instance
    @Bean
    public RestTemplate restTemplate(){

        return new RestTemplate();
    }

    @Reference(timeout = 1)
    private SampleApi sampleApi;

    public static void main(String[] args) throws InterruptedException {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosConsumerApplication.class, args);
//        while(true) {
//            //When configurations are refreshed dynamically, they will be updated in the Enviroment, therefore here we retrieve configurations from Environment every other second.
//            String userName = applicationContext.getEnvironment().getProperty("user.name");
//            String userAge = applicationContext.getEnvironment().getProperty("user.age");
//            System.err.println("user name :" + userName + "; age: " + userAge);
//            TimeUnit.SECONDS.sleep(1);
//        }
    }

}
